<?php
namespace im\controllers;

use Yii;
use yii\web\Controller;
use common\component\exception\ErrMap;
use common\models\OperationLog;
use common\models\App;
use common\component\tool\Tool;

class BasicController extends Controller
{
    protected $get;
    protected $post;
    protected $headers;
    protected $session;
    protected $appid;//对外
    protected $app_id;//对内
    protected $comid;
    protected $app_info_id;
    
    /*所有控制器，必须执行的方法 优先于beforeAction前执行*/
    public function init()
    {
        $this->get = Yii::$app->request->get();
        $this->post = Yii::$app->request->post();
        $this->headers = Yii::$app->request->headers;
        $this->session = Yii::$app->session;
    }

    public function beforeAction($action)
    {
        $module = $this->module->id;
        $controller = $this->id;
        $action = $this->action->id;
        // echo $module . '-' . $controller . '-' . $action;die;

        $origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '*';
        // P($origin);
        // $origin = '*';
        if(in_array($origin, Yii::$app->params['allow_origin'])){
            header('Access-Control-Allow-Origin:'.$origin);
            header('Access-Control-Allow-Methods:POST,GET'); 
            header('Access-Control-Allow-Credentials:true');

            if($controller == 'instance' and $action == 'list'){//访问的是所有实例控制器
                return true;
            }
            /*如果存在appid, 根据appid得到app_id*/
            if(isset($this->get['appid']) or isset($this->post['appid'])){
                if(isset($this->get['appid'])){
                    $this->appid = $this->get['appid'];
                }
                if(isset($this->post['appid'])){
                    $this->appid = $this->post['appid'];
                }
                // P($this->appid);
                $app = App::find()->select(['app_id', 'comid', 'app_info_id'])
                                  ->where('appid = :appid', [':appid' => $this->appid])
                                  ->one();
                // P($app);
                if(isset($app->app_id)){
                    $this->app_id = $app->app_id;
                    $this->app_info_id = $app->app_info_id;
                    $this->comid = $app->comid;
                    return true;
                }else{
                    list($errno, $errmsg) = ErrMap::getError(405);//实例不存在
                }
            }else{
                list($errno, $errmsg) = ErrMap::getError(405);//实例不存在
            }
        }

        //非合法域
        if(!isset($errno) and !isset($errmsg)){
            list($errno, $errmsg) = ErrMap::getError(404);//访问的文件飞走了
        }
        $args = array(
            'loginid' => 0,
            'loginname' => '',
            'back_code' => $errno,
            'back_info' => $errmsg,
        );
        if(gettype($res = OperationLog::addLog($args)) != 'boolean'){//操作日志
            Yii::$app->end($res);
        };
    }


}
